//
//  FPPublicConmmandVC.m
//  ForestPack
//
//  Created by jimmy on 2018/7/13.
//  Copyright © 2018年 郑洲. All rights reserved.
//


///这个是发布需求的控制器界面
#import "FPPublicConmmandVC.h"
#import "FPPublicDemandCell.h"
#import "SimpleHeaderView.h"
#import "CompleteConmmandInfoViewController.h"
#import "FPSubmitOrderVC.h"

@interface FPPublicConmmandVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UITextFieldDelegate,CTAssetsPickerControllerDelegate,UINavigationBarDelegate,UITextFieldDelegate,UITextViewDelegate>

@property (nonatomic,strong)  BaseTableView  * tableView;
@property (nonatomic,strong)  void(^needType)(NSString *type);
@property (nonatomic,copy)    NSString       * phoneNum;
@property (nonatomic,copy)    NSString       * typeStr;
@property (nonatomic,copy)    NSString       * contentStr;
@property (nonatomic,strong)  UITextView     * contentText;
@property (nonatomic,strong)  FPCustomButton * addPhotoBtn;

@property (nonatomic,strong)  NSMutableArray  * picsArray;
@property (nonatomic,strong)  NSMutableArray  * picsUrlArray;
@property (nonatomic,assign)  NSInteger         picsCount;

@end

@implementation FPPublicConmmandVC

- (NSMutableArray *)picsArray
{
    if (_picsArray == nil) {
        _picsArray = [[NSMutableArray alloc] init];
    }
    return _picsArray;
}

- (NSMutableArray *)picsUrlArray
{
    if (_picsUrlArray == nil) {
        _picsUrlArray = [[NSMutableArray alloc] init];
    }
    return _picsUrlArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitle:@"发布需求"];
    
    [self setTableViewUI];
    
    self.typeStr = @"";
}

-(void)updateData
{
    FPPublicDemandCell *demandCell = [self.view viewWithTag:1000];
    demandCell.grayTextF.text = self.typeStr;
    NSString *typeStr = demandCell.grayTextF.text;
    
    FPBudgetcell *budgetcell = [self.view viewWithTag:1001];
    NSString *budgeStr = budgetcell.contentText.text;
    
    if (typeStr.length <= 0 || budgeStr.length <= 0 || self.contentText.text.length <= 0 || self.picsArray.count <= 0) {
        [HttpManager showNoteMsg:@"请填写完整的需求后再提交"];
        return;
    }else{
        [self uploadPics];
    }
}

-(void)uploadPics
{
    WeakObj(self);
    [HttpManager uploadImageArr:self.picsArray success:^(id successResponse) {
        selfWeak.picsUrlArray = successResponse;
        [selfWeak uploadCommendData];
    }];
}

-(void)uploadCommendData
{
    if (self.picsUrlArray.count <= 0) {
        return;
    }
    
    NSString * main_pic = @""; /// [0], [1]
    for (NSString * urlStr in self.picsUrlArray) {
        if ([main_pic isEqualToString:@""]) {
            main_pic = urlStr;
        }else{
            main_pic = [NSString stringWithFormat:@"%@,%@",main_pic, urlStr]; /// [0], [1]
        }
    }
    NSString *url = [NSString stringWithFormat:@"%@app/order_review",REQUESTHEADER];//添加商品
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        [dict setValue:[FPLoginAndRegisterTools getToken] forKey:@"token"];
    //    [dict setValue:@(self.shop_id) forKey:@"shop_id"];//店铺id
    //    [dict setValue:@(self.order_id) forKey:@"order_id"];//订单id
    //    [dict setValue:@(self.order_no) forKey:@"order_no"];//订单号
        [dict setValue:self.contentStr forKey:@"content"];//内容
        [dict setValue:main_pic forKey:@"pic"];//详情图（两个url之间以逗号隔开）
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [HttpManager showNoteMsg:@"提交成功"];
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                FPSubmitOrderVC *submitOrderVC = [[FPSubmitOrderVC alloc] init];
                [self.navigationController pushViewController:submitOrderVC animated:true];
            });
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

-(void)setTableViewUI
{
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:self.tableView];
}

-(void)addPhotoClicked
{
    self.picsCount = 9 - self.picsArray.count;
    if (self.picsCount == 0) {
        return;
    }
    [self alterIconPortrait];
}

#pragma mark----- 选择弹出框
-(void)alterIconPortrait
{
    //弹出提示框
    __weak typeof(self)weakSelf = self;
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：拍摄
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf openCamare];
    }]];
    //按钮：从手机相册选择
    [alert addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [weakSelf openAlbum];
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 打开相册
-(void)openAlbum
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status != PHAuthorizationStatusAuthorized) {
            return ;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            // init Picker弹出图片选择界面
            CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
            //隐藏空相册
            picker.showsEmptyAlbums = NO;
            //允许显示图片选中后的顺序
            picker.showsSelectionIndex = YES;
            //选择需要弹出的相册，一般我们只需要弹出相机胶卷和自定义相册即可
            picker.assetCollectionSubtypes = @[@(PHAssetCollectionSubtypeSmartAlbumUserLibrary),@(PHAssetCollectionSubtypeAlbumRegular)];
            // picker delegate
            picker.delegate = self;
            // present picker
            [self presentViewController:picker animated:YES completion:nil];
        });
    }];
}

#pragma mark - 打开相机
-(void)openCamare
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.allowsEditing = YES;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate  图片处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSLog(@"Picker returned successfully.");
    //    将选择的图片在imageView上显示
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [self.picsArray addObject:image];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    //处理完毕，回到个人信息页面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    NSLog(@"Picker was cancelled");
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 设置图片最多选九张
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    NSInteger max = self.picsCount;
    if (picker.selectedAssets.count < max) return YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意" message:[NSString stringWithFormat:@"最多选择%ld张图片",(long)max] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    //一定要用picker 不能用self 因为当前显示在最上面的控制器是picker 而不是self
    [picker presentViewController:alert animated:YES completion:nil];
    
    return NO;
}

#pragma mark - 选择完毕的时候调用
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    // 关闭图片选择界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    //选择图片时的配置项 (如果不写配置项 会导致请求的图片尺寸出现问题)
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    //遍历图片选择的图片显示成九宫格样式
    for (NSInteger i = 0; i < assets.count; i ++) {
        PHAsset *asset = assets[i];
        CGFloat scale = UIScreen.mainScreen.scale;
        CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
        
        //请求图片 (需要先用图片管理员请求图片数据 请求完成后 在block里添加图片)
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            WeakObj(self);
            [selfWeak.picsArray addObject:result];
            if (i == assets.count - 1) {
                [self.tableView reloadData];
            }
        }];
    }
}

/** 移除某一张照片*/
- (void)removeImage:(UIButton *)button
{
    [self showAlert:button];
}

- (void)showAlert:(UIButton *)button
{
    WeakObj(self);
    //显示提示框
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil  message:@"删除已选择的图片"  preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault   handler:^(UIAlertAction * action) {
        //响应事件
        [selfWeak.picsArray removeObjectAtIndex:button.tag - 3000];
        [selfWeak reloadDetail];
        NSLog(@"action = %@", action);
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel   handler:^(UIAlertAction * action) {
        //响应事件
        NSLog(@"action = %@", action);
        
    }];
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

/** 重新加载照片*/
- (void)reloadDetail
{
    /** 刷新*/
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - TableView的代理和数据源
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    }else{
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        NSLog(@" section-1-0 %f", 44.0);
        NSLog(@"segmentIndex --------");
        return ScreenX375(44);
    }else if (indexPath.section == 0){
        if (indexPath.row == 0 || indexPath.row == 1) {
            NSLog(@" section-0-0-1 %f", 44.0);
            return ScreenX375(44);
        }else{
            if (self.picsArray.count != 0) {
                CGFloat a = ScreenX375(200) + (self.picsArray.count / 3 + 1) * ScreenX375(110) + self.picsArray.count / 3 * ScreenX375(10);
                 NSLog(@" section-0-2 %f", a);
                return a ;
            }else{
                NSLog(@" section-0-2==0 %f", 169.0);
                return ScreenX375(300);
            }
        }
        
    }else{
        NSLog(@" section-2-0 %f", 169.0);
        return ScreenX375(169);
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return ScreenX375(53);
    }else{
        return 0.01;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        //您选择了：森林包装（这是要网络请求获取到的数据）：为您服务
        SimpleHeaderView *view = [SimpleHeaderView headerViewWithTitle:@"您选择了森林包装为您服务" withHeight:53];
        view.backgroundColor = [UIColor whiteColor];
        return view;
    }else{
        UIView *view= [[UIView alloc] init];
        return view;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        return 0.01;
    }else{
        return ScreenX375(10);
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            FPPublicDemandCell *cell = [FPPublicDemandCell cellWithTableView:tableView andIndexPath:indexPath];
            cell.tag = 1000;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            if (self.typeStr) {
                cell.grayTextF.text = self.typeStr;
                cell.grayTextF.textColor = FONTCOLOR_BLACK;
            }
            return cell;
        }else if (indexPath.row == 1){
            FPBudgetcell *budgetcell = [FPBudgetcell cellWithTableView:tableView andIndexPath:indexPath];
            budgetcell.tag = 1001;
            budgetcell.contentText.delegate = self;
            return budgetcell;
        }else{
            UITableViewCell *demondDesCell = demondDesCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DemondDesCell"];

            demondDesCell.selectionStyle = UITableViewCellSelectionStyleNone;
            for (UIView *subView in demondDesCell.subviews) {
                [subView removeFromSuperview];
            }
            
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(10), ScreenX375(70), ScreenX375(15))];
            titleLabel.text = @"需求描述:";
            titleLabel.textColor = FONTCOLOR_BLACK;
            titleLabel.font = Kfont(14);
            [demondDesCell addSubview:titleLabel];
            
            self.contentText = [[UITextView alloc] init];
            self.contentText.frame = CGRectMake(13, titleLabel.bottom + ScreenX375(8), SCREEN_WIDTH - ScreenX375(26), ScreenX375(120));
            self.contentText.textColor = REXADECIMALCOLOR(@"#999999");
            self.contentText.text = @"请写详细需求，已便为您精准匹配专业人才";
            self.contentText.text = self.contentStr;
            self.contentText.delegate = self;
            self.contentText.textAlignment = NSTextAlignmentLeft;
            self.contentText.font = Kfont(14);
            self.contentText.layer.borderWidth = 1;
            self.contentText.layer.borderColor = RGB_COLOR(220,220,220).CGColor;
            [demondDesCell addSubview:self.contentText];
            
            CGFloat margin = (SCREEN_WIDTH - ScreenX375(26) - ScreenX375(330)) / 2;
            for (int i = 0; i < self.picsArray.count; i++) {
                CGFloat x = i % 3 * (ScreenX375(110) + margin) + ScreenX375(13);
                CGFloat y = i / 3 * ScreenX375(120) + ScreenX375(178);
                UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, ScreenX375(110), ScreenX375(110))];
                imageV.image = self.picsArray[i];
                imageV.userInteractionEnabled = YES;
                [demondDesCell addSubview:imageV];
                /** 为图片添加一个右上角的删除按钮*/
                UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                CGFloat removeX = ScreenX375(110) - ScreenX375(20);
                CGFloat removeW = ScreenX375(24);
                removeBtn.frame = CGRectMake(removeX, -12, removeW, removeW);
                [removeBtn setImage:[UIImage imageNamed:@"案例删除"] forState:UIControlStateNormal];
                [removeBtn addTarget:self action:@selector(removeImage:) forControlEvents:UIControlEventTouchUpInside];
                removeBtn.tag = i + 3000;
                [imageV addSubview:removeBtn];
            }
            if (self.picsArray.count != 9) {
                self.addPhotoBtn = [[FPCustomButton alloc] init];
                self.addPhotoBtn.frame = CGRectMake(self.picsArray.count % 3 * (ScreenX375(110) + margin) + ScreenX375(13), self.picsArray.count / 3 * ScreenX375(120) + ScreenX375(178), ScreenX375(110), ScreenX375(110));
                //self.addPhotoBtn.frame = CGRectMake(13, self.contentText.bottom + ScreenX375(10), ScreenX375(110), ScreenX375(110));
                [self.addPhotoBtn setBackgroundImage:[UIImage imageNamed:@"虚线边框"] forState:UIControlStateNormal];
                [self.addPhotoBtn setImage:[UIImage imageNamed:@"添加图片"] forState:UIControlStateNormal];
                [self.addPhotoBtn setTitle:@"添加图片" forState:UIControlStateNormal];
                [self.addPhotoBtn setTitleColor:RGB_COLOR(210,210,210) forState:UIControlStateNormal];
                self.addPhotoBtn.titleLabel.font = Kfont(14);
                [self.addPhotoBtn addTarget:self action:@selector(addPhotoClicked) forControlEvents:UIControlEventTouchUpInside];
                [demondDesCell addSubview:self.addPhotoBtn];
            }
            return demondDesCell;
        }
    }
    else if (indexPath.section == 1) {
        FPPublicDemandPhoneNumCell *cell = [FPPublicDemandPhoneNumCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.tag = 2000;
        cell.changePhoneNum = ^{
            [self showAlertList];
        };
        cell.phoneNum.text = self.phoneNum;
        cell.phoneNum.text = [self.phoneNum stringByReplacingCharactersInRange:NSMakeRange(3, 4)  withString:@"****"];
        
        return cell;
    }
    else{
        FPPublicDemandBottomCell *bottomCell = [FPPublicDemandBottomCell cellWithTableView:tableView andIndexPath:indexPath];
        bottomCell.tag = 3000;
        bottomCell.label.hidden = YES;
        bottomCell.selectBtn.hidden = YES;
        
        bottomCell.submitClick = ^{
            [self updateData];
            
        };
        return bottomCell;
    }
}

- (void)showAlertList
{
    //提示框添加文本输入框
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:@"请输入手机号码" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        //响应事件
        //得到文本信息
        for(UITextField *text in alert.textFields){
            NSLog(@"text = %@", text.text);
            if (text.text.length != 11) {
                [HttpManager showNoteMsg:@"请重新输入正确的手机号码"];
                return ;
            }
            self.phoneNum = text.text;
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"请输入手机号码";
    }];
    
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:false];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            //这个点击选择服务类型后要将内容传到上个界面显示cell上面
            CompleteConmmandInfoViewController *vc = [[CompleteConmmandInfoViewController alloc] init];
            WeakObj(self);
            vc.needType = ^(NSString *type) {
                selfWeak.typeStr = type;
                /** 刷新*/
                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
                [selfWeak.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            };
            
            [self.navigationController pushViewController:vc animated:true];
        }
    }else if(indexPath.section == 1){
        if (indexPath.row == 0) {
            //修改按钮的点击事件
        }
    }
    
}

-(void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"请写详细需求，已便为您精准匹配专业人才"]) {
        textView.textColor = [UIColor blackColor];
        textView.text = @"";
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length < 1) {
        textView.textColor = REXADECIMALCOLOR(@"#999999");
        textView.text = @"请写详细需求，已便为您精准匹配专业人才";
    }
    self.contentStr = self.contentText.text;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return [textField resignFirstResponder];
}

/*
 //            if (cell == nil) {
 //                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
 //            }
 //            cell.textLabel.text = @"您想要做：请选择类目";
 //            cell.textLabel.font = Kfont(14);
 //            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString: @"您想要做：请选择类目"];
 //            NSRange range1 = [[str string] rangeOfString:@"您想要做："];
 //            [str addAttribute:NSForegroundColorAttributeName value:FONTCOLOR_BLACK range:range1];
 //            NSRange range2 = [[str string] rangeOfString:@"请选择类目"];
 //            [str addAttribute:NSForegroundColorAttributeName value:RGB_COLOR(194,194,194) range:range2];
 //            cell.textLabel.attributedText = str;
 //            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
 
 */

@end
